<template>
  <div class="stock-out">
    <div class="card stock-out__header">
      <el-form inline>
        <el-form-item label="物品类型">
          <el-cascader
            v-model="params.goodsTypeId"
            :options="goodsTypeOptions"
            :props="{ value: 'id', label: 'name' }"
            clearable
          />
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="params.applyUserName" placeholder="申请人姓名" clearable />
        </el-form-item>

        <el-form-item label="审核人">
          <el-input v-model="params.examineUserName" placeholder="审核人姓名" clearable />
        </el-form-item>

        <el-form-item label="审核状态">
          <el-select
            v-model="params.state"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in examineStateFormat"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            size="medium"
            type="danger"
            @click="handleReset"
          >重置</el-button>

          <el-button
            size="medium"
            type="primary"
            @click="handleSearch"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="card stock-out__content">
      <div class="stock-out__content__header">
        <el-button
          type="primary"
          @click="handleOpenCreateDialog"
        >
          出库申请
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
      >
        <el-table-column
          label="物品名称"
          align="center"
          prop="stockOutDetail.goodsType.name"
        />

        <el-table-column
          label="出库数量"
          align="center"
          prop="stockOutDetail.quantity"
        />

        <el-table-column
          label="单位"
          align="center"
          prop="stockOutDetail.unit_name"
        />

        <el-table-column
          prop="conversion_ratio"
          label="单位换算比例(主/辅)"
          align="center"
        >
          <template v-slot="{ row }">
            {{ getConversionRatioFormat(row) }}
            <!--            {{ row.unit_id ? `${row.conversion_ratio} : 1` : '-' }}-->
          </template>
        </el-table-column>

        <el-table-column
          label="申请原因"
          align="center"
          prop="stockOutDetail.reason"
          show-overflow-tooltip
        />

        <el-table-column
          label="申请人"
          align="center"
          prop="stockOutDetail.applyUser.username"
        />

        <el-table-column
          label="审核状态"
          align="center"
          prop="status"
        >
          <template v-slot="{ row }">
            <el-tag
              :type="examineState[row.status].tagType"
            >
              {{ examineState[row.status].label }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="审核人"
          align="center"
          prop="examine_user_id"
        >
          <template v-slot="{ row }">
            {{ row.examine_user_id ? row.examineUser?.username : '-' }}
          </template>
        </el-table-column>

        <el-table-column
          label="审核时间"
          align="center"
          prop="examine_time"
        />

        <el-table-column
          label="操作"
          align="center"
        >
          <template v-slot="{ row }">
            <el-button
              :disabled="row.status !== 0"
              size="mini"
              type="text"
              @click="handleOpenEditDialog(row)"
            >
              编辑
            </el-button>

            <el-dropdown trigger="click" @command="handleDropdownItemClick($event, row.id)">
              <span class="el-dropdown-link">
                <el-button
                  style="margin-left: 10px;"
                  :disabled="row.status !== 0"
                  size="mini"
                  type="text"
                >
                  审核
                </el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="success">通过</el-dropdown-item>
                <el-dropdown-item command="failed">拒绝</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

          </template>
        </el-table-column>
      </el-table>

      <div class="stock-out__content__pagination">
        <Pagination
          style="margin-top: 0; padding: 0;"
          :total="total"
          :limit="params.paginate"
          @pagination="pagination"
        />
      </div>
    </div>

    <CreateStockOutDialog
      ref="createStockOutDialogRef"
      :visible.sync="createDialogVisible"
      :goods-type-options="goodsTypeOptions"
      :loading="dialogConfirmBtnLoading"
      @confirm="handleCreateConfirm"
    />

    <EditStockOutDialog
      :visible.sync="editDialogVisible"
      :goods-type-options="goodsTypeOptions"
      :loading="dialogConfirmBtnLoading"
      :details="stockOutDetail"
      @confirm="handleEditConfirm"
    />
  </div>
</template>
<script>
import {
  getStockOutRecords,
  createStockOut,
  editStockOut,
  getGoodsType,
  examineStockOut
} from '@/api/officeSuppliesManagement'
import { findAllParent, sleep } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'
import CreateStockOutDialog from '@/views/officeSuppliesManagement/components/stockOut/CreateStockOutDialog.vue'
import EditStockOutDialog from '@/views/officeSuppliesManagement/components/stockOut/EditStockOutDialog.vue'
export default {
  name: '',
  components: {
    Pagination,
    CreateStockOutDialog,
    EditStockOutDialog
  },
  data() {
    return {
      list: [],
      params: {
        goodsTypeId: null,
        time: [],
        applyUserName: '',
        examineUserName: '',
        state: null,
        page: 1,
        paginate: 10
      },
      total: 0,
      loading: false,
      examineState: {
        0: {
          label: '待审核',
          tagType: 'info',
          value: 'wait'
        },
        1: {
          label: '审核成功',
          tagType: 'success',
          value: 'success'
        },
        2: {
          label: '审核失败',
          tagType: 'danger',
          value: 'failed'
        }
      },
      goodsTypeOptions: [],
      createDialogVisible: false,
      dialogConfirmBtnLoading: false,
      examineInfo: {
        id: null,
        state: '',
        failed_reason: null
      },
      editDialogVisible: false,
      stockOutDetail: null
    }
  },
  computed: {
    examineStateFormat() {
      return Object.values(this.examineState).map(item => {
        return {
          label: item.label,
          value: item.value
        }
      })
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      Promise.allSettled([
        this.getStockOutRecords(),
        this.getGoodsType()
      ])
    },

    async getStockOutRecords() {
      this.loading = true
      try {
        const res = await getStockOutRecords(this.generateParams())
        console.log('res --------->', res)
        this.list = res.data
        this.total = res.meta.total
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      } finally {
        await sleep()
        this.loading = false
      }
    },

    async getGoodsType() {
      try {
        const res = await getGoodsType()
        this.goodsTypeOptions = res.data
      } catch (error) {
        throw new Error(error?.response?.data?.message || '信息获取失败')
      }
    },

    generateParams() {
      const len = this.params.goodsTypeId?.length
      const goodsTypeId = len > 0 ? this.params.goodsTypeId[len - 1] : null
      return {
        ...this.params,
        time: this.params.time.length ? JSON.stringify(this.params.time) : null,
        goodsTypeId
      }
    },

    handleSearch() {
      this.params.page = 1
      this.getStockOutRecords()
    },

    handleReset() {
      this.params = this.$options.data().params
      this.getStockOutRecords()
    },

    getConversionRatioFormat(row) {
      const { stockOutDetail } = row
      const mainUnit = stockOutDetail?.goodsType?.goods_type_main_unit?.name
      return stockOutDetail?.unit_id ? `${stockOutDetail.conversion_ratio}${mainUnit} = 1${stockOutDetail.unit_name}` : '-'
    },

    pagination(page) {
      this.params.page = page.page
      this.params.paginate = page.limit
      this.getStockOutRecords()
    },

    handleOpenCreateDialog() {
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs.createStockOutDialogRef.resetFields()
      })
    },

    handleCreateConfirm(e) {
      console.log('e --------->', e)
      const params = {
        ...e,
        goods_type_id: e.goods_type_id[e.goods_type_id.length - 1]
      }
      this.createStockOutFetch(params)
    },

    async createStockOutFetch(params) {
      this.dialogConfirmBtnLoading = true
      try {
        const res = await createStockOut(params)
        this.$message.success('申请成功')
        this.createDialogVisible = false
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '申请失败')
      } finally {
        this.dialogConfirmBtnLoading = false
      }
    },

    refresh() {
      this.params = this.$options.data().params
      this.getStockOutRecords()
    },

    handleDropdownItemClick(command, id) {
      this.examineInfo.id = id
      this.examineInfo.state = command
      const handle = {
        success: this.examineSuccessConfirm,
        failed: this.examineFailedConfirm
      }

      handle[command]()
    },

    examineSuccessConfirm() {
      this.$confirm(
        '是否确定审核通过？',
        '提示',
        {
          type: 'warning',
          showCancelButton: true
        }
      ).then(() => {
        this.examineStockOutFetch(this.examineInfo)
      })
    },

    examineFailedConfirm() {
      this.$prompt(
        '请输入拒绝原因',
        '拒绝原因',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (val) => {
            return !!val
          },
          inputErrorMessage: '拒绝原因不能为空'
        }
      ).then(res => {
        this.examineInfo.failed_reason = res.value
        this.examineStockOutFetch(this.examineInfo)
      })
    },

    async examineStockOutFetch(params) {
      try {
        const res = await examineStockOut(params)
        this.$message.success('审核成功')
        this.refresh()
        this.examineInfo = this.$options.data().examineInfo
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '审核失败')
      }
    },

    handleOpenEditDialog(row) {
      console.log('row --------->', row)
      const { id, stockOutDetail } = row
      this.stockOutDetail = {
        id,
        unit_id: stockOutDetail.unit_id,
        reason: stockOutDetail.reason,
        quantity: stockOutDetail.quantity,
        goods_type_id: this.goodsTypeIdFormat(stockOutDetail.goods_type_id)
      }

      this.editDialogVisible = true
    },

    goodsTypeIdFormat(id) {
      const result = findAllParent(this.goodsTypeOptions, id)
      if (Array.isArray(result)) {
        result.push(id)
      }
      return result ?? []
    },

    handleEditConfirm(e) {
      console.log('e --------->', e)
      const params = {
        ...e,
        goods_type_id: e.goods_type_id[e.goods_type_id.length - 1]
      }
      this.editStockOutFetch(params)
    },

    async editStockOutFetch(params) {
      this.dialogConfirmBtnLoading = true
      try {
        const res = await editStockOut(params)
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改失败')
      } finally {
        this.dialogConfirmBtnLoading = false
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.stock-out {
  padding: 20px;

  &__header {
    padding: 20px 20px 0 20px !important;
    ::v-deep(.el-form-item) {
      margin-bottom: 20px;
      margin-right: 20px;
      //padding: 0 20px;
    }
  }

  &__content {

    &__header {
      margin-bottom: 20px;
    }

    &__pagination {
      margin-top: 20px;
      display: flex;
      justify-content: end;
    }
  }

  .card {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 20px;
  }
}
</style>
